package com.baselib;

/**
 * script Name: Example_server.java
 * @author 	Zhikun Cai @ Thomson Beijing office
 * @version	1.0
 * function:	Example server using tunnel.
 * date:	2008-09-17
 * update date:  
 * update item:  
 */

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class Example_Server{

	public static void main(String[] args) {
		ServerSocket server = null;
		try {
			server = new ServerSocket(8888);
			while (true) {
				Socket requestSocket = server.accept();
				System.out.println("Accept From "+requestSocket.getInetAddress()+':'+requestSocket.getPort());
				responseThread t = new responseThread(requestSocket);
				t.setDaemon(true);
				t.start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


class responseThread extends Thread {
	private Socket socket;
	
	responseThread(Socket socket) {
		this.socket = socket;
	}
	public void run() {
		Tunnel t = null;
		try {
			t = new Tunnel(socket);
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		while (true) {
			Message msg = t.receive();
			
			
			if (msg == null) {
				System.err.println(t.getErrorInfo());
				break;
			}	
            //must add the com.tlrg.nsa.util to the same directory,so it's function can be used.			
			
			System.out.println("The guid is:"+msg.getBody());
			try {t.send("<guid>"+msg.getBody()+"</guid>");}
			catch (SocketException e) {}
		}
	}
}
